package com.share.util;

import com.share.controller.BaseController;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author sunxuejian
 * @date 2020/10/8
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Object bean = handlerMethod.getBean();
        if(isAnoymous(handlerMethod)) {
            return true;
        }
        Cookie[] cookies = request.getCookies();
        String token = null;
        for(Cookie cookie : cookies) {
            if("access_token".equals(cookie.getName())){//判断当前Cookie中的name是否是想要的cookie
                token = cookie.getValue();
            }
        }

        if(StringUtils.isEmpty(token)) {
            //转到登录页面
            return false;
        }
        //token校验
        if(checkToken(token) != null) {
            BaseController baseController = (BaseController)bean;
            baseController.setUid(checkToken(token));
            return true;
        }
        return false;
    }

    private String checkToken(String token) {
        Claims claims = JwtTokenUtil.phaseToken(token);
        String  uid = (String)claims.get("uid");
        return uid;


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private boolean isAnoymous(HandlerMethod handlerMethod) {
        Object bean = handlerMethod.getBean();
        Class clazz = bean.getClass();
        if(clazz.getAnnotation(Anoymous.class) != null) {
            return true;
        }
        Method method = handlerMethod.getMethod();
        if(method.getAnnotation(Anoymous.class) != null) {
            return true;
        }
        return false;
    }

}
